package com.chaucer.dynamicdemo.config;

import com.chaucer.dynamicdemo.enums.DynamicSourceEnum;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * @Description TODO
 * @Author li
 * @Date 2021/9/3 12:01
 */
@Slf4j
public class DataSourceUtils {
    private static final Object LOCK = new Object();
    public static final String DATASOURCE_SUFFIX = "DataSource";

    public static HikariDataSource getDataSourceFromJDBC(Environment env, String prefix) {
        HikariDataSource ds = new HikariDataSource();
        String url = env.getProperty(prefix + ".db.url");
        String ip = env.getProperty(prefix + ".db.ip");
        String port = env.getProperty(prefix + ".db.port");
        String dbName = env.getProperty(prefix + ".db.dbName");
        String userName = env.getProperty(prefix + ".db.userName");
        String password = env.getProperty(prefix + ".db.password");
        if (StringUtils.isEmpty(url) &&
                (StringUtils.isEmpty(ip) || StringUtils.isEmpty(port) || StringUtils.isEmpty(dbName))) {
            log.warn("若需按jdbc的方式配置 请配置 url 或者 ip port dbName");
            return null;
        }
        if (StringUtils.isEmpty(userName) ) {
            log.warn("若需按jdbc的方式配置 请配置 userName password ");
            return null;
        }
        if (StringUtils.isEmpty(url)) {
            StringBuilder sb = new StringBuilder();
            sb.append("jdbc:mysql://");
            sb.append(ip);
            sb.append(":");
            sb.append(port);
            sb.append("/");
            sb.append(dbName);
            url = sb.toString();
        }
        ds.setJdbcUrl(url);
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }


    public static String selectDataSource() {
        synchronized (LOCK) {
            String source = DynamicThreadLocal.get();
            DynamicSourceEnum[] values = DynamicSourceEnum.values();
            for (DynamicSourceEnum value : values) {
                if (Objects.equals(source, value.getCode())) {
                    return source + DATASOURCE_SUFFIX;
                }
            }

            return DynamicSourceEnum.Inner.getCode() + DATASOURCE_SUFFIX;
        }
    }

//


}